package com.blade.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Properties;

import static org.apache.commons.lang3.StringUtils.removeStart;

/**
 * 用于读取属性文件
 * 这里读取的是类路径下的appconfig/serviceenv.properties
 */
public class ResUtils {
    private static Properties props;

    static {
        try {
            Resource resource = new ClassPathResource("appconfig/serviceenv.properties");
            props = PropertiesLoaderUtils.loadProperties(resource);
            System.out.println(props.getProperty("ResBase"));
        } catch (Exception e) {
            System.err.println("初始化配置文件appconfig/serviceenv.properties异常");
        }
    }

    public static String res(String resPath) {
        StringBuffer res = new StringBuffer(props.getProperty("ResBase"))
                .append("/")
                .append(removeStart(resPath, "/"))
                .append("?ResVer=")
                .append(props.getProperty("ResVer"));
        return res.toString();
    }

    public static String action(String resPath) {
        StringBuffer res = new StringBuffer(props.getProperty("action"))
                .append("/")
                .append(removeStart(resPath,"/"));
        return res.toString();
    }

    public static String config(String resPath) {
        StringBuffer res = new StringBuffer(props.getProperty("ResBase"))
                .append("/")
                .append(removeStart(resPath, "/"));
        return res.toString();
    }

    /**
     * 根据属性文件的属性名得到属性值
     * @param key 属性名
     * @return 属性值
     */
    public static String getKey(String key) {
        return props.getProperty(key);
    }

    public static String getKey(String key, String defaultVal) {
        String val = props.getProperty(key);
        return StringUtils.isEmpty(val) ? defaultVal : val;
    }

}
